﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpenseSystem.Model;
using ExpenseSystem.Lor;
using ExpenseSystem.Common;
using ExpenseSystem.DataUpdater;
using ExpenseSystem.Fether;
using ExpenseSystem.DataUpdater.Validation;

namespace ExpenseSystem.Core.ProductionModules
{
    public class BlandUpdaterRegister
    {
        int rows;
        public NormalDataUpdater<BlandModel> GetBlandUpdater()
        {
            NormalDataUpdater<BlandModel> systemDataUpdater = new NormalDataUpdater<BlandModel>();
            systemDataUpdater.DataUpdating += DataNotSpaceValid;
            systemDataUpdater.DataUpdating += SingletonValid;
            systemDataUpdater.DataDeleting += CheckAvaliable;
            return systemDataUpdater;
        }
        private void CheckAvaliable(object sender, DataValidationEventArgs<BlandModel> e)
        {
            ProductionFetcher productionFetcher = new ProductionFetcher();
            string message;
            if (productionFetcher.ListByBland(e.Delete.Site, e.Delete.AutoId, out message, out rows).Count > 0)
            {
                e.Cancle = true;
                e.Message = "本档案已经被占用";
                return;
            }
        }

        private void SingletonValid(object sender, DataValidationEventArgs<BlandModel> e)
        {
            BlandFetcher blandFetcher = new BlandFetcher();
            string message = "";
            BlandModel bland = blandFetcher.GetByCode(e.Insert.Site, e.Insert.Code, out message);
            if (bland != null && bland.AutoId != e.Insert.AutoId)
            {
                e.Cancle = true;
                e.Message = String.Format("代号[{0}]已被[{1}]占用", bland.Code, bland.Name);
                return;
            }
        }

        private void DataNotSpaceValid(object sender, DataValidationEventArgs<BlandModel> e)
        {
            if (String.IsNullOrWhiteSpace(e.Insert.Code))
            {
                e.Message = "代号不能为空";
                e.Cancle = true;
                return;
            }
            if (String.IsNullOrWhiteSpace(e.Insert.Name))
            {
                e.Message = "名称不能为空";
                e.Cancle = true;
                return;
            }
        }
    }
}
